// src/hooks/useI18n.js
import { createContext, useContext, useState, useMemo, useEffect } from 'react'
import locales, { LangType } from './locales'
import { settingStore } from '@/store/settingStore'

// 创建上下文
const I18nContext = createContext(null)
const buildT =
  (getLang: () => LangType) =>
  (key: string, options: Record<string, string> = {}) => {
    const keys = key.split('.')
    // @ts-ignore
    let text: string = keys.reduce(
      // @ts-ignore
      (obj, k) => obj?.[k] || key,
      locales[getLang()]
    )
    // 替换占位符
    Object.entries(options).forEach(([k, v]) => {
      text = text.replace(new RegExp(`\\{${k}\\}`, 'g'), v)
    })
    return text
  }

// 提供器组件：包裹根组件
export const I18nProvider = ({
  children,
}: {
  children: React.ReactNode
  defaultLang?: LangType
}) => {
  const [lang, setLang] = useState<LangType>(settingStore.value.lang)

  // 翻译函数：支持占位符（如 t('greeting', { name: '张三' })）
  const t = buildT(() => lang)
  useEffect(() => {
    if (settingStore.value.lang != lang) {
      settingStore.setValue('lang', lang)
    }
  }, [lang])
  // 缓存上下文值，避免不必要的重渲染
  const value = useMemo(() => ({ lang, setLang, t }), [lang])

  return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>
}

// 自定义 Hook：在组件中使用
export const useI18n = () => useContext(I18nContext)

export const t = buildT(() => settingStore.value.lang)
